//  Inside Microsoft Exchange 2007 Web Services 
//  Chapter 18
//
//  Copyright (c) 2007 David Sterling, Ben Spain, Mark Taylor, Huw Upshall, Michael Mainer.  
//  All rights reserved.
//

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using ProxyHelpers.EWS;

namespace ParsingPropertyPathFromErrorWithMapper
{
    class Program
    {
        static void Main(string[] args)
        {
            ExchangeServiceBinding binding = new ExchangeServiceBinding();
            binding.Url = @"https://yourServer/ews/Exchange.asmx";
            binding.Credentials = new NetworkCredential("username", "password", "domain");

            CreateItemSetItemIdAndFailWithMapper(binding);
        }

        /// <summary>
        /// Tries to create an invalid item and then parses out the property path 
        /// from the response message (Listing 18-9)
        /// </summary>
        /// <param name="binding">Binding to use for the call</param>
        /// 
        public static void CreateItemSetItemIdAndFailWithMapper(
                               ExchangeServiceBinding binding)
        {
            // Create our request
            //
            CreateItemType request = new CreateItemType();
            request.Items = new NonEmptyArrayOfAllItemsType();
            ItemType itemToCreate = new ItemType();
            itemToCreate.ItemId = new ItemIdType();
            itemToCreate.ItemId.Id = "This is a bad id";
            itemToCreate.Subject = "I cannot succeed";

            request.Items.Items = new ItemType[] { itemToCreate };
            // Make the call...
            //
            CreateItemResponseType response = binding.CreateItem(request);

            // Remember, all of the success/failure information is on the base type.  
            // No need to cast when checking this information.
            //
            ResponseMessageType responseMessage =
                          response.ResponseMessages.Items[0];
            if (responseMessage.ResponseCode != ResponseCodeType.NoError)
            {
                // we want to look at the offending property here...
                //
                BasePathToElementType[] paths = null;
                if (FieldURIMapper.TryExtractFieldURIsFromResponseMessage(
                                    responseMessage,
                                    out paths))
                {
                    foreach (BasePathToElementType path in paths)
                    {
                        // do something with the paths.
                    }
                }
            }
        }
    }
}
